<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getClues">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="sellerAssign" :disabled="this.sels.length===0">分配营销人员</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleChangeBusiness" :disabled="this.sels.length===0">转化</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="50">
			</el-table-column>
			<el-table-column prop="fullName" label="全名称" width="120" sortable>
			</el-table-column>
      <el-table-column prop="appellation" label="名称" width="80" sortable>
      </el-table-column>
      <!--0表示未分配 1表示跟进 2表示已转化为商机 -1放入线索池-->
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='0'" style="color: blue">未分配</span>
          <span v-if="scope.row.state=='1'" style="color: gold">跟进中</span>
          <span v-if="scope.row.state=='2'" style="color: green">已转化</span>
          <span v-if="scope.row.state=='-1'" style="color: red">已废弃</span>
        </template>
      </el-table-column>
      <el-table-column prop="company" label="公司" width="80" sortable>
      </el-table-column>
			<el-table-column prop="job" label="职业" width="100" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="200" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="200" sortable>
			</el-table-column>
			<el-table-column prop="mphone" label="移动电话" width="200" sortable>
			</el-table-column>
			<el-table-column prop="address" label="地址" width="200" sortable>
			</el-table-column>
			<el-table-column prop="source" label="来源" width="200" sortable>
			</el-table-column>

			<el-table-column prop="createBy" label="创建人" width="80" sortable>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="200" sortable>
			</el-table-column>
			<el-table-column prop="editBy" label="修改人" width="80" sortable>
			</el-table-column>
			<el-table-column prop="editTime" label="修改时间" width="200" sortable>
			</el-table-column>
			<el-table-column prop="description" label="描述" width="200" sortable>
			</el-table-column>
			<el-table-column prop="contactSummary" label="接触总结" width="200" sortable>
			</el-table-column>
			<el-table-column prop="nextContactTime" label="下次接触时间" width="200" sortable>
			</el-table-column>
			<el-table-column prop="seller.username" label="营销人员" width="100" sortable>
			</el-table-column>
			<!--<el-table-column prop="sex" label="性别" width="100" :formatter="formatSex" sortable>
			</el-table-column>-->
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleActivity(scope.$index, scope.row)">参与活动</el-button>
					<el-button size="small" @click="handleFollowUp(scope.$index, scope.row)" :disabled="scope.row.state!=1">跟进</el-button>
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增或编辑界面
		v-model="saveFormVisible" 老版本用
		:visible.sync 新版本用
		-->
		<el-dialog title="新增或编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="clue" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名字" prop="name">
					<el-input v-model="clue.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="优惠方式">
          <el-input v-model="clue.preferential_method_id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_date">
          <el-input v-model="clue.start_date" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_date">
          <el-input v-model="clue.end_date" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="clue.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建时间时间" prop="create_time">
          <el-input v-model="clue.create_time" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建人" prop="create_by">
          <el-input v-model="clue.create_by" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="最近修改时间" prop="edit_time">
          <el-input v-model="clue.edit_time" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="修改人" prop="edit_by">
          <el-input v-model="clue.edit_by" auto-complete="off"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

    <el-dialog title="参与活动" :visible.sync="activityFormVisible" :close-on-click-modal="false">
        <el-checkbox-group
            v-model="clueActivitys.activityIds"
            >
          <el-checkbox v-for="ac in activityList" :label="ac.id">{{ac.name}}</el-checkbox>
        </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="activityFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="avtivitySubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配营销人员" :visible.sync="sellerFormVisible" :close-on-click-modal="false">
      <el-form :model="clue" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="全称" prop="fullName">
          <el-input v-model="clue.fullName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="clue.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="clue.source" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="clue.description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="营销人员" prop="seller">
          <el-select v-model="clue.seller" placeholder="请选择" value-key="id">
            <!--key唯一标识
                label选择之后显示到选择框中的值
                value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"-->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="sellerFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="sellerSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="跟进" :visible.sync="followUpFormVisible" :close-on-click-modal="false">
      <el-form :model="clueRemark" label-width="80px">
        <el-form-item label="线索">
          <el-input v-model="clueRemark.clue.fullName" auto-complete="off"readonly></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="noteContent">
          <el-input v-model="clueRemark.noteContent" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="followUpFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="followUpSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="转化商机" :visible.sync="clueBusinessVisible" :close-on-click-modal="false">
      <el-form :model="clueBusiness.clue" label-width="80px"  ref="clueBusinessForm">
        <el-form-item label="姓名">
          <el-input v-model="clueBusiness.clue.fullName"  disabled="disabled" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="clueBusiness.clue.phone" disabled="disabled" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="clueBusiness.product" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
               必须要写  value-key="id"
            -->
            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="clueBusinessVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueBusinessSubmit">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
			  query:{
          currentPage: 1,//当前页码
          pageSize:10,//每页显示多少条
          keyword:''//关键字
        },
        pageInfo:{
          total:0,//总数 默认是0
          rows:[],//页面数据
          totalPage:0//页面数据条数
        },
				listLoading: false,
				sels: [],//列表选中列
        //新增和编辑的数据
        clue:{
          id:null,
          fullName:'',
          appellation: '',
          company: '',
          job: '',
          email: '',
          phone: '',
          mphone: '',
          address: '',
          source:null,
          state:null,
          createBy:'',
          createTime:'',
          editBy:'',
          editTime:'',
          description:'',
          contactSummary:'',
          nextContactTime:'',
          seller:{}//营销人员
        },
        employees:[],/*保存员工（营销人员）数据*/
				saveFormVisible: false,//新增或编译界面是否显示
        activityFormVisible: false,//选择活动窗口
        sellerFormVisible: false,//分配营销人员窗口
        followUpFormVisible:false,//跟进窗口
        clueBusinessVisible:false,//转化成商机
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入标题名字', trigger: 'blur' }
					]
				},
        clueActivitys:{
			    clueId:null,
          activityIds:[]
        },
        activityList:[],
        clueRemark: {
          id: null,
          noteContent: '',
          clue: {}
        },
        clueBusiness:{//商机包含线索和商品才能转化成商机
				  clue:{},
          product:{}
        },
        products:[]
			}
		},
		methods: {
		  //转化成商机
      clueBusinessSubmit(){
        // console.log(this.clueBusiness)
        this.$http.post("/clue/business",this.clueBusiness)
            .then(result=>{
              result = result.data;
              if (result.success){
                this.$message({
                  message: '操作成功！',
                  type: 'success'
                });
                this.clueBusinessVisible = false;
                this.getClues(); //刷新表格
              }else{
                this.$message({
                  message: '转化失败！'+result.message,
                  type: 'error'
                });
              }

            })
            .catch(result=>{
              this.$message({
                message: '系统错误！',
                type: 'error'
              });
            })
      },
		  //打开商机转化框
      handleChangeBusiness(){
        if(this.sels.length>1){
          this.$message({
            message: '请选择一个',
            type: 'error'
          })
        } else{
          //回显
          this.clueBusiness.clue = this.sels[0];
          if(this.clueBusiness.clue.state!=1){
            this.$message({
              message: '请选择一个处于跟进状态的线索',
              type: 'error'
            })
          }else{
            this.getProducts()
            this.clueBusinessVisible = true;

            //修改线索状态
            //线索备注
            //添加商机，-选择一个产品
            //添加线索产品

          }
        }
      },
		  //获取商品信息
      getProducts(){
        this.$http.get("/product")
            .then(result =>{
              result = result.data;
              if (result.success){
                this.products = result.data;
              }else{
                this.$message({
                  message: '获取产品数据失败！'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              this.$message({
                message: '系统错误！',
                type: 'error'
              });
            })
      },
		  //线索跟进备注
      followUpSubmit(){
        // console.log(this.clueRemark)
        let para = Object.assign({}, this.clueRemark);
        this.$http.put("/clueRemark",para)
            .then(result => {
              result = result.data
              if(result.success){
                //NProgress.done();
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.$refs['saveForm'].resetFields();//重置表单
                this.getClues();//保存完重新获取系统数据
                this.saveFormVisible = false;//关闭对话框
              }else{
                this.$message({
                  message: '保存失败',
                  type: 'error'
                })
              }
            })
        this.followUpFormVisible = false;
      },
      //打开线索跟进备注框
      handleFollowUp(index,row){
        this.clueRemark={
              id: null,
              noteContent: '',
              clue: {}
        }
        this.clueRemark.clue = row;
        console.log(this.clueRemark);
        this.followUpFormVisible =true;
      },
		  //提交营销人员分配
      sellerSubmit(){
        console.log(this.clue)
        let para = Object.assign({}, this.clue);
        console.log(para)
        this.$http.post("/clue/assign",para)
            .then(result => {
              result = result.data
              if(result.success){
                //NProgress.done();
                this.$message({
                  message: '分配成功',
                  type: 'success'
                })
                this.$refs['saveForm'].resetFields();//重置表单
                this.getClues();//保存完重新获取系统数据
                this.saveFormVisible = false;//关闭对话框
              }else{
                this.$message({
                  message: '分配失败',
                  type: 'error'
                })
              }
            })
            .catch(result=>{
              this.$message({
                message: '分配异常',
                type: 'error'+result.message
              })
            });
        this.sellerFormVisible = false
      },
		  //打开分配营销人员弹框
      sellerAssign(){
        if(this.sels.length>1){
          this.$message({
            message: '请选择一个',
            type: 'error'
          })
        } else{
          //回显
          this.clue = this.sels[0]
          if(this.clue.state!=0){
            this.$message({
              message: '请选择一个未分配的线索',
              type: 'error'
            })
          }else{
            this.getEmployees()
            this.sellerFormVisible = true;
          }
        }
      },
      //获取员工
      getEmployees() {
        this.$http.get("/employee")
            .then(result=>{
              result = result.data
              if(result.success){
                this.employees = result.data;
              }else {
                this.$message({
                  message: '获取数据失败！'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              console.log("出错了"+result.message)
            })
      },
		  //获取可参与活动
		  getActivityList(){
        this.listLoading = true;
        this.$http.post("/activity/list")
            .then(result=>{
              result = result.data
              if(result.success){
                this.activityList = result.data;
              }else {
                this.$message({
                  message: '获取活动数据失败！'+result.message,
                  type: 'error'
                });
              }
              this.listLoading = false;
            })
            .catch(result=>{
              console.log("出错了"+result.message)
            })
      },
      //性别显示转换
			/*formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.se.x == 0 ? '女' : '未知';
			},*/
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getClues();
			},
			//获取部门列表
			getClues() {
				this.listLoading = true;
				this.$http.post("/clue",this.query)
                  .then(result=>{
                    result = result.data
                    if(result.success){
                      this.pageInfo.total = result.total;
                      // this.clues = result.data.clues;
                      this.pageInfo=result.data
                    }else {
                      this.$message({
                        message: '获取分页数据失败！'+result.message,
                        type: 'error'
                      });
                    }
                    this.listLoading = false;
                  })
                  .catch(result=>{
                    console.log("出错了"+result.message)
                  })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
          let id = row.id;
					this.$http.delete("/clue/"+id)
              .then(result => {
                //NProgress.done();
                result = result.data
                if(result.success){
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else{
                  this.$message({
                    message: '删除失败',
                    type: 'error'
                  });
                }
                this.getClues();
                this.listLoading=false
              })
              .catch(result=>{
                this.$message({
                  message: '异常',
                  type: 'error'+result.message
                });
              })
				}).catch(() => {
          this.$message({
            message: '取消成功',
            type: 'error'
          });
				});
			},
      //显示参与活动窗口
      handleActivity($index, row){
        this.clueActivitys.clueId = row.id
        this.getActivityList();
        this.activityFormVisible=true;
      },
      avtivitySubmit(){
        // console.log(this.clueActivitys)
        this.$http.put("/clue/assoc",this.clueActivitys)
            .then(result => {
              result = result.data
              if(result.success){

                //NProgress.done();
                this.$message({
                  message: '成功参加',
                  type: 'success'
                })
                this.$refs['saveForm'].resetFields();//重置表单
                this.getClues();//保存完重新获取系统数据
                this.saveFormVisible = false;//关闭对话框
              }else{
                this.$message({
                  message: '参加失败',
                  type: 'error'
                })
              }
            })
            .catch(result=>{
              this.$message({
                message: '异常',
                type: 'error'+result.message
              })
            });
        this.saveLoading = false;//关闭加载条
      },
			//显示编辑界面
			handleEdit: function (index, row) {
			  //回显
        this.clue = Object.assign({}, row);
        let path = this.clue.type.path; //完整的path 包含自己的
        if (path){
          let paths = path.split("/"); //根据/分割
          let idsStr = paths.slice(1,paths.length);
          let idsInt = [];
          for (let i = 0; i <idsStr.length ; i++) {//封装成数组
            idsInt.push(parseInt(idsStr[i]));
          }
          // console.log(idsInt);
          //做部门的回显
          this.clue.type = idsInt;//这里部门就变成了一个数组
        }
        this.saveFormVisible = true;
			},
			//显示新增界面
			handleAdd: function () {
			  //清空
        this.clue={
          id: null,
          name: '',
          preferential_method_id: null,
          start_date: '',
          description: ''
        }
				this.saveFormVisible = true;
			},
			//保存
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.clue);
              //把数据转换成我们想要格式 parent: [1, 2]---》parent:{id:2} 只需要一个上级部门id 不需要爷爷级的
              if (para.type){
                let typeIds = para.type; // [1, 2]
                let typeId = typeIds[typeIds.length-1]; // 2
                para.type = {"id":typeId} //type:{id:2}
              }
							// para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							this.$http.put("/clue",para)
                  .then(result => {
                    result = result.data
                    if(result.success){
                      //NProgress.done();
                      this.$message({
                        message: '保存成功',
                        type: 'success'
                      })
                      this.$refs['saveForm'].resetFields();//重置表单
                      this.getClues();//保存完重新获取系统数据
                      this.saveFormVisible = false;//关闭对话框
                    }else{
                      this.$message({
                        message: '保存失败',
                        type: 'error'
                      })
                    }
                  })
                  .catch(result=>{
                    this.$message({
                      message: '保存失败',
                      type: 'error'+result.message
                    })
                  });
                this.saveLoading = false;//关闭加载条
							});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			  let ids=[]//存放选中的id 传入后端的是一个数组
			  for(var i=0;i<this.sels.length;i++){
			    ids.push(this.sels[i].id)
        }
			  // console.log(ids)

				// var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = {ids: ids};
					this.$http.patch("/clue",ids)
              .then(result => {
                result = result.data
                this.listLoading = false;
                //NProgress.done();
                if(result.success){
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else {
                  this.$message({
                    message: '删除失败',
                    type: 'error'+result.message
                  });
                }
                this.getClues();
              });
				}).catch(() => {
				});
			}
		},
		mounted() {
			this.getClues();
		}
	}

</script>

<style scoped>

</style>